import { defineStore } from 'pinia'
import { ref, computed } from 'vue'
import axios from 'axios'

export const useAuthStore = defineStore('auth', () => {
  const token = ref('')
  const user = ref(null)
  const isLoggedIn = computed(() => !!token.value)

  const login = async (username: string, password: string) => {
    try {
      const response = await axios.post('/auth/login', {
        username,
        password,
      })

      token.value = response.data.data.token
      user.value = response.data.data.user

      localStorage.setItem('token', token.value)
      localStorage.setItem('user', JSON.stringify(user.value))

      return true
    } catch (error) {
      console.log('登录失败', error);
      throw error
    }
  }

  const logout = () => {
    token.value = ''
    user.value = null
    localStorage.removeItem('token')
    localStorage.removeItem('user')
    axios.defaults.headers.common['Authorization'] = null
  }

  const initAuth = () => {
    const storedToken = localStorage.getItem('token')
    const storedUser = localStorage.getItem('user')

    if (storedToken) {
      token.value = storedToken
      user.value = JSON.parse(storedUser!)
      axios.defaults.headers.common['Authorization'] = `Bearer ${storedToken}`
    }
  }

  return {
    token,
    user,
    isLoggedIn,
    login,
    logout,
    initAuth,
  }
})
